package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dal.Crud;

/**
 * Servlet implementation class CSRServlet
 */
public class CSRServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CSRServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("userId") != null) {
			
			getServletContext().getRequestDispatcher("/pages/csr.jsp").forward(
					request, response);

		} else {
			response.getOutputStream()
					.write("Access denied.".getBytes());
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {

			String csr = request.getParameter("csr");
			Integer userId = (int) request.getSession().getAttribute("userId");
			if (csr != null) {

				if (userId != null) {
					Crud crud = new Crud();
					boolean i = crud.addCSR(userId, csr);

					if (i == true)
						response.getOutputStream().write(
								"Demende prise en comprte".getBytes());
					else
						response.getOutputStream().write(
								"Demende non prise en compte".getBytes());
				} else {
					response.getOutputStream().write(
							"You're not connected".getBytes());
				}

			} else {
				response.getOutputStream().write("Invalid CSR".getBytes());
			}

		} catch (Exception e) {
			e.printStackTrace();
			response.getOutputStream().write(e.getMessage().getBytes());
		}
	}
}
